<template>
  <!-- Header 组件 -->
  <Header></Header>
  <!-- 面包屑导航 -->
  <Crumb>购物车页</Crumb>
  <!-- 主要内容 -->
  <div class="mt-1" v-if="data.myCart.length>0">
    <el-row justify="space-between" class="title">
      <el-col :span="6"><h2>购物车</h2></el-col>
      <el-col :span="18" class="right">
        已选商品（不含运费）<span class="price"><span class="yen">&yen;</span>{{ total }}</span>
        <el-button type="danger" @click="settlement"> 提交订单</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mt-2">
      <el-col :offset="1" :span="2">
        <el-checkbox label="全选" v-model="data.all" @click="allSelect"></el-checkbox> 
      </el-col>
      <el-col :span="9">商品信息</el-col>
      <el-col :span="3">价格</el-col>
      <el-col :span="4">数量</el-col>
      <el-col :span="3">小计</el-col>
      <el-col :span="1">操作</el-col>
    </el-row>
    <el-row v-for="(item,i) in data.myCart" :key="i" :gutter="10" align="middle" class="row">
      <el-col :span="1" :offset="1"><el-checkbox  v-model="item.checked"></el-checkbox></el-col>
      <el-col :span="3"><div class="img"><img :src="item.img"></div></el-col>
      <el-col :span="7">{{ item.desc }}</el-col>
      <el-col :span="3">{{ item.price }}</el-col>
      <el-col :span="4"><el-input-number v-model="item.num" :min="0" /></el-col>
      <el-col :span="3"><span class="price"><span class="yen">&yen;</span>{{ item.price*item.num }}</span></el-col>
      <el-col :span="1" class="pointer">
          <el-popconfirm onfirm-button-text="是" cancel-button-text="否" :icon="InfoFilled"
            icon-color="#626AEF" title="你真的要删除此件商品吗?"
            @confirm="confirmEvent(item.cid)"
            @cancel="cancelEvent">
            <template #reference>
              <el-icon :size="18"><Delete /></el-icon>
            </template>
          </el-popconfirm>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="title">
      <el-col :offset="1" :span="2">
        <el-checkbox label="全选" v-model="data.all" @click="allSelect"></el-checkbox> 
      </el-col>
      <el-col :span="6" :offset="3">已选商品 <span class="num">{{ sum }}</span>  件</el-col>
      <el-col :span="12" style="text-align: right;">
        合计（不含运费）：<span class="price"><span class="yen">&yen;</span>{{ total }}</span>
        <el-button type="danger" @click="settlement"> 提交订单</el-button>
      </el-col>
    </el-row> 
  </div>
  <div v-else>
    <p class="empty">购物车为空，赶紧浏览商品去购物吧!</p>
  </div>
  <!-- Footer 组件 -->
  <Footer></Footer>
</template>

<script setup>
import Header from "@/components/Header.vue"   //@是./src目录的别名，在vite.config.js配置
import Footer from "@/components/Footer.vue"
import Crumb from "@/components/Crumb.vue"
import { reactive,computed,getCurrentInstance,onMounted } from 'vue'
import { useRoute,useRouter } from "vue-router"
import { Delete,InfoFilled } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()  //获取当前实例的代理对象proxy
const route = useRoute()
const router = useRouter()
const data = reactive({
  myCart:[],
  all:false,
  inverse:false
})

//总计价格
const total=computed(()=>{
  let length = data.myCart.length;
  let sum=0
  for(let i=0;i<length;i++) {
    if(data.myCart[i].checked) {
      sum+=data.myCart[i].price * data.myCart[i].num;
    }
  }
  return sum.toFixed(2);
})
//总计商品件数
const sum=computed(()=>{
  let length = data.myCart.length;
  let sum=0
  for(let i=0;i<length;i++) {
    if(data.myCart[i].checked) {
      sum++
    }
  }
  return sum;
})

//全选
let allSelect = ()=>{
  let length = data.myCart.length;
  if(!data.all){
    for(let i=0;i<length;i++) {
      if(!data.myCart[i].checked) {
        data.myCart[i].checked=true
      }
    }
  }else {
    for(let i=0;i<length;i++) {
      if(data.myCart[i].checked) {
        data.myCart[i].checked=false
      }
    }
  }
}

//确认从购物车删除商品
const confirmEvent = (cid) => {
  let length = data.myCart.length;
  for(let i=0;i<length;i++) {
    if(data.myCart[i].cid==cid){
      data.myCart.splice(i,1)
      break;
    }
  }
  //更新购物车
  localStorage.setItem("myCart",JSON.stringify(data.myCart))
}

//结算，提交到订单
let settlement=()=>{
  //创建订单数组
  const orders=[]
  let length = data.myCart.length
  for(let i=0;i<length;i++) {
    if(data.myCart[i].checked) {    //购物车中选中的商品
      const order ={}               //创建订单对象
      order.id=orderCode()          //生成订单号
      order.img = data.myCart[i].img
      order.desc=data.myCart[i].desc
      order.price = data.myCart[i].price
      order.num=data.myCart[i].num
      order.timestamp = new Date().getTime()  //当前时间戳
      order.status=i%4+1                 //模拟订单的状态 1：待付款，2：待发货 3：待收货 4：待评价
      orders.push(order)                 //添加到订单数组
    }
  }
  console.log(orders)
  //从localstorage中读出保存的订单
  let myOrders = JSON.parse(localStorage.getItem("myOrders") || '[]');
  //添加订单到我的订单
  myOrders.push(...orders)
  
  //保存订单
  localStorage.setItem("myOrders",JSON.stringify(myOrders))
  //跳转到订单页
  router.push("/order")
}

//随机生成订单号
const orderCode = ()=>{
  var orderCode='';
  for (var i = 0; i < 6; i++)   //6位随机数，用以加在时间戳后面。
  {
    orderCode += Math.floor(Math.random() * 10);
  }
  orderCode = new Date().getTime() + orderCode;  //时间戳，用来生成订单号。
  return orderCode;
}

//获取购物车数据
const getShoppingCart = ()=>{
  const token = sessionStorage.getItem("token");   //读取当前登录信息
  if(token) {
    data.myCart=JSON.parse(localStorage.getItem("myCart"))
  }else{
    alert("你还未登录，请先登录!")
    router.push("/login")
  }
}

onMounted(()=>{
  getShoppingCart()
  // localStorage.clear()
})
</script>

<style scoped>
.title{
  height: 60px;
  line-height: 60px;
  border-bottom: 1px solid #ccc;
}
.img{
  width:100%;
  height: 120px;
  text-align: center;
}
.img>img{
  width:70%;
  position: relative;
  top:50%;
  transform: translateY(-50%); 
  border-radius: 3px;
}
.row{
  margin:10px 0;
  text-align:center;
  background-color: rgb(244, 241, 238);
  border-radius: 10px;
}
.price,.num {
  font-weight: bold;
  color: red;
  font-size:1.1rem;
  padding-right:3px;
}
.yen{
  font-size:0.8rem;
  padding-right: 3px;
}
</style>